package asia.njut.reader.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import asia.njut.reader.R;
import asia.njut.reader.R.layout;
import asia.njut.reader.R.menu;
import asia.njut.reader.activity.LoginActivity.UserLoginTask;
import asia.njut.reader.model.Friend;
import asia.njut.reader.view.PullRefreshListView;
import asia.njut.reader.view.PullRefreshListView.OnRefreshListener;

public class FriendsActivity extends Activity implements OnRefreshListener  {

	private PullRefreshListView mRefreshListView;
	private List<Map<String, Object>> mDataSource= new ArrayList<Map<String, Object>>();
	private listViewAdapter mAdapter;
	private int pageSize = 10;
	private List<Map<String, Object>> mylist;
	private UserFriendsTask mFriendsTask = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friends);
		
		ActionBar bar = this.getActionBar();
		bar.setDisplayHomeAsUpEnabled(true);
		bar.setDisplayShowTitleEnabled(true);
		bar.setTitle(R.string.friends_list);
		
		 mylist= new ArrayList<Map<String, Object>>();
		 
		mFriendsTask = new UserFriendsTask();
		mFriendsTask.execute((Void) null);
		
		
		mRefreshListView = (PullRefreshListView) findViewById(R.id.main_listview);
		 System.out.println("mylist.size"+mylist.size());
		mDataSource.addAll(mylist);
		//mDataSource = Friend.initValue(1, 15,mylist);
		
		 System.out.println("mDataSource.size"+mDataSource.size());
	   
		
		
		mAdapter = new listViewAdapter();
		mRefreshListView.setAdapter(mAdapter);
		mRefreshListView.setonRefreshListener(this);
		
	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			return true;
		default:
			return false;
		}
	}
	
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.friends, menu);
		return true;
	}
	
	
	
	
	
	
	
	private class listViewAdapter extends BaseAdapter {
		int count = mDataSource.size();

		@Override
		public int getCount() {
			return count;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = LayoutInflater.from(FriendsActivity.this).inflate(
					R.layout.booklistview_item, null);
			TextView title = (TextView) view.findViewById(R.id.item_title);
			TextView text = (TextView) view.findViewById(R.id.item_subtext);
			title.setText(mDataSource.get(position).get("title").toString());
			text.setText(mDataSource.get(position).get("subtext").toString());
			return view;
		}

	}

	private void chageListView(int pageStart, int pageSize) {
		List<Map<String, Object>> data = Friend.initValue(pageStart,
				pageSize);
		for (Map<String, Object> map : data) {
			this.mDataSource.add(map);
		}
		data = null;
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mAdapter.count += pageSize;
			mAdapter.notifyDataSetChanged();
			mRefreshListView.onRefreshComplete();
			super.handleMessage(msg);
		}
	};

	@Override
	public void onPullUpRefresh() {
		new Thread() {
			public void run() {
				try {
					//模拟网络请求时间
					Thread.sleep(3 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				chageListView(mDataSource.size() + 1, pageSize);
				handler.sendEmptyMessage(0);
			}
		}.start();
	}

	@Override
	public void onPullDownRefresh() {
		new Thread() {
			public void run() {
				try {
					Thread.sleep(3 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				chageListView(mDataSource.size() + 1, pageSize);
				handler.sendEmptyMessage(0);
			}
		}.start();
	}
	
	
	
	
	
	
	
	
	public class UserFriendsTask extends AsyncTask<Void, Void, Boolean> {
		
		
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			HttpClient httpclient = new DefaultHttpClient();
			// 你的URL
			HttpPost httppost = new HttpPost("http://192.168.137.1/bookshare/mobile/user/follow/id/1/mobile/yes");
			String strResult = "";
			try {
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						2);
			
				nameValuePairs.add(new BasicNameValuePair("mobile", "yes"));

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf8"));
				HttpResponse response = httpclient.execute(httppost);
				/* 若状态码为200，Post成功 */
				if (response.getStatusLine().getStatusCode() == 200) {
					/* 读返回数据 */
					strResult = EntityUtils.toString(response.getEntity());
				} else {
					strResult = "Error Response:"+ response.getStatusLine().toString();
							
							
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			strResult = strResult.trim();
		

		
			// TODO: 登陆用户的判断.
			try {
			    JSONTokener jsonParser = new JSONTokener(strResult);  

			    JSONObject loginInfo = (JSONObject) jsonParser.nextValue(); 
		
			    if(loginInfo.getInt("status")==0){ //没有关注
			    	return false;
			    }else {
				    JSONTokener infoData = new JSONTokener(loginInfo.getString("info"));  
				    System.out.println(loginInfo.getString("info"));
				    JSONArray info = new JSONArray(infoData);  
				    Map<String, Object> map;
				    for (int i = 0; i < info.length(); i++) {  
				        JSONObject temp = (JSONObject) info.get(i);  
				        String friend_id = temp.getString("friend_id");  
				        System.out.println("friend_id："+friend_id);
				        String user_id_from = temp.getString("user_id_from");  
				        String user_id_at = temp.getString("user_id_at");  
				        String timestamp = temp.getString("timestamp"); 
				        map = new HashMap<String, Object>();
						map.put("title", friend_id );
					    map.put("subtext", timestamp);
				        mylist.add(map);
				       
				    } 
					 System.out.println("doInBackground:mylist.size:"+mylist.size());

			    	return true;
				}
			    

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			

		
			
			
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			

			if (success) {
					 
				Toast.makeText(getApplicationContext(), "成功",
					     Toast.LENGTH_SHORT).show();
				
				 System.out.println("onPostExecute:mylist.size:"+mylist.size());

	               
			} else {
				 
				Toast.makeText(getApplicationContext(), "失败",
					     Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onCancelled() {
			
		}
	}

}
